package com.srwl.mytx.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.activity.BaseActivity;
import com.srwl.mytx.activity.ChatRoomActivity;
import com.srwl.mytx.activity.ConversationActivity.SystemNotifyActivity;
import com.srwl.mytx.activity.DonationDetailActivity;
import com.srwl.mytx.activity.WithdrawActivity;
import com.srwl.mytx.activity.WithdrawDetailActivity;
import com.srwl.mytx.domain.LiveRoom;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.utils.ClickUtil;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.ChatActivity;
import com.srwl.mytx.activity.ForwardDetailsActivity;
import com.srwl.mytx.activity.ConversationActivity.NotifyActivity;
import com.srwl.mytx.activity.TopicDetailsActivity;
import com.srwl.mytx.activity.VerifyTopicActivity;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Donation;
import com.srwl.mytx.domain.Forward;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.Transfer;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.Utils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 系统通知适配器
 * <p>
 */
public class SystemNotifyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final String TAG = "SystemNotifyAdapter";
    private Context context;
    private List<Message> messageList;
    private NotifyMessageInteractionListener listener;


    public SystemNotifyAdapter(Context context, List<Message> messageList, NotifyMessageInteractionListener listener) {
        this.context = context;
        this.messageList = messageList;
        this.listener = listener;
    }

    @Override
    public int getItemViewType(int position) {
        return messageList.get(position).getSubType();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        //下面使用通用的布局
        View view = LayoutInflater.from(context).inflate(R.layout.notify_message_normal_item_layout, parent, false);
        return new SystemMsgViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
        Message notify = messageList.get(position);
        if (holder instanceof SystemMsgViewHolder) {

            SystemMsgViewHolder systemMsgViewHolder = (SystemMsgViewHolder) holder;
            systemMsgViewHolder.tv_title.setText(notify.getTitle());
            systemMsgViewHolder.tv_date.setText(DateUtils.getTimestampString(notify.getCreated()));
            String content = "";
            switch (notify.getSubType()) {
                case Constant.PUSH_MESSAGE_PERSON_RECEIVED_FORWARD:
                    Forward forward = JSONObject.parseObject(notify.getExtraData(), Forward.class);
                    systemMsgViewHolder.itemView.setOnClickListener(v -> {
                        if (!ClickUtil.isFastClick()) {
                            toForwardDetail(forward.getfId());
                        }
                    });
                    String forwardContent = "收到一笔转赠,金额：" + Utils.moneyFormat(forward.getAmount()) + "，点击查看转赠详情";
                    systemMsgViewHolder.tv_content.setText(forwardContent);
                    break;

                case Constant.PUSH_MESSAGE_PERSON_RECEIVED_DONATION:
                    Donation donation = JSONObject.parseObject(notify.getExtraData(), Donation.class);
                    User targetUser = donation.getTargetUser();
                    String username = "";
                    if (targetUser != null) {
                        username = targetUser.getUsername() != null ? targetUser.getUsername() : targetUser.getNick();
                    }
                    String donationContent = "收到[ " + username + " ]的捐赠,金额：" + Utils.moneyFormat(donation.getAmount()) + "，点击查看捐赠详情";
                    systemMsgViewHolder.tv_content.setText(donationContent);
                    systemMsgViewHolder.itemView.setOnClickListener(v -> {
                        if (!ClickUtil.isFastClick()) {
                            DonationDetailActivity.startActivity(context, donation.getId());
                        }
                    });
                    break;
                case Constant.PUSH_MESSAGE_TOPIC_VERIFY:
                    handleTopicVerifyNotify(notify, systemMsgViewHolder);
                    break;

                case Constant.PUSH_MESSAGE_APPLY_WITHDRAW: {
                    Transfer transfer = JSONObject.parseObject(notify.getExtraData(), Transfer.class);
                    if (transfer == null) return;
                    systemMsgViewHolder.itemView.setOnClickListener(v -> WithdrawActivity.startActivity(context, transfer));
                    User targetUser1 = transfer.getTargetUser();
                    if (targetUser1 != null) {
                        content = "[ " + targetUser1.getUsername() + " ]的提现申请，金额:" + transfer.getAmount();
                    } else {
                        content = notify.getContent();
                    }
                    systemMsgViewHolder.tv_content.setText(content);
                    systemMsgViewHolder.tv_date.setText(DateUtils.getTimestampString(notify.getCreated()));
                }
                break;
                case Constant.PUSH_MESSAGE_WITHDRAW_COMPLETE:
                    Transfer transfer = JSONObject.parseObject(notify.getExtraData(), Transfer.class);
                    if (transfer == null) return;
                    systemMsgViewHolder.itemView.setOnClickListener(v -> WithdrawDetailActivity.startActivity(context, transfer.getId()));
                    systemMsgViewHolder.tv_content.setText(notify.getContent());
                    systemMsgViewHolder.tv_date.setText(DateUtils.getTimestampString(notify.getCreated()));
                    break;


                case Constant.PUSH_MESSAGE_LIVE_ACCUSATION:
                case Constant.PUSH_MESSAGE_LIVE_ERROR_REPORT:
                    LiveRoom liveRoom = JSONObject.parseObject(notify.getExtraData(), LiveRoom.class);
                    if (liveRoom == null) return;
                    String content1 = notify.getContent();
                    systemMsgViewHolder.itemView.setOnClickListener(v -> ChatRoomActivity.startActivity(context, liveRoom));
                    systemMsgViewHolder.tv_content.setText(content1);
                    systemMsgViewHolder.tv_date.setText(DateUtils.getTimestampString(notify.getCreated()));
                    break;

            }
        }

    }

    /**
     * 处理主题审核通知
     *
     * @param notify
     * @param systemMsgViewHolder
     */
    private void handleTopicVerifyNotify(Message notify, SystemMsgViewHolder systemMsgViewHolder) {
        Topic verifyTopic = JSONObject.parseObject(notify.getExtraData(), Topic.class);
        if (verifyTopic == null) {
            return;
        }
        boolean isTopicManger;
        User manager = verifyTopic.getManager();
        if (manager != null) {
            isTopicManger = UserProfileManager.getInstance().getLoginUserInfo().getuId().equals(manager.getuId());
        } else {
            isTopicManger = true;//在通知消息中，没回传 主题创建者的时候，说明是发给主题创建者的
        }
        String content = "";
        if (verifyTopic.getStatus() == Constant.TOPIC_STATUS_WAIT_VERIFY) {

            content = "有新建焦点需要审核:[ " + verifyTopic.getTitle() + " ],点击处理";
        } else if (verifyTopic.getStatus() == Constant.TOPIC_STATUS_VERIFY_FAIL) {
            content = "焦点:[ " + verifyTopic.getTitle() + " ], 未通过审核,查看详情";
        } else if (verifyTopic.getStatus() == Constant.TOPIC_STATUS_NORMAL) {
            if (isTopicManger) {
                content = "焦点:[ " + verifyTopic.getTitle() + " ], 审核通过，希望在您的管理之下，该焦点能日益壮大；注意：管理者10天未登录，视为放弃管理权限，将自动清除该焦点管理者";
            } else {
                content = "焦点:[ " + verifyTopic.getTitle() + " ], 审核已通过";
            }

        }
        systemMsgViewHolder.tv_content.setText(content);
        systemMsgViewHolder.itemView.setOnClickListener(v -> context.startActivity(new Intent(context, VerifyTopicActivity.class).putExtra(Constant.EXTRA_INFO_MESSAGE, notify)));
        systemMsgViewHolder.tv_date.setText(DateUtils.getTimestampString(notify.getCreated()));
    }

    /**
     * 跳转到提现订单详情
     *
     * @param transfer
     */
    private void toTransferDetail(Transfer transfer) {
        Intent intent = new Intent(context, WithdrawActivity.class);
        intent.putExtra(Constant.EXTRA_INFO_TRANSFER, transfer);
        intent.putExtra("getTaskInfo", true);
        ((Activity) context).startActivityForResult(intent, NotifyActivity.REQUEST_CODE_TO_TRANSFER_DETAIL);
    }

    @Override
    public int getItemCount() {
        return messageList.size();
    }


    public class SystemMsgViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_title)
        TextView tv_title;
        @BindView(R.id.tv_content)
        TextView tv_content;
        @BindView(R.id.tv_date)
        TextView tv_date;

        public SystemMsgViewHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);

        }
    }


    private void contact(String targetUserId) {
        User userInfo = Helper.getInstance().queryUserInfoById(targetUserId);
        if (userInfo != null) {
            context.startActivity(new Intent(context, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, userInfo));
        } else {
            getFullUserInfo(targetUserId);
        }
    }

    void toForwardDetail(String forwardId) {
        ForwardDetailsActivity.startActivity(context, forwardId);
    }

    private void getFullUserInfo(String userId) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }

        RetrofitManager.getInstance().createRequest(UserService.class)
                .getUserInfo(userId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            // showToast(tv_customerService, getString(R.string.system_busy));
                            return;
                        }
                        JSONObject object = (JSONObject) result.getData();
                        //把用户作为临时联系人 保存在数据库
                        User userInfo = object.toJavaObject(User.class);
                        userInfo.setType(Constant.USER_TYPE_TEMP);
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(userInfo);
                        context.startActivity(new Intent(context, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, userInfo));

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        // showToast(tv_customerService, getString(R.string.system_busy));
                    }
                });


    }

    /**
     * 跳转到主题详情
     */
    private void toTopicDetail(Topic topic) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        //跳转之前查询使用topicId去服务端查询详细的主题信息
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .getTopicFromMysql(topic.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            //showToast("系统繁忙");
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            // showToast("系统繁忙");
                            return;
                        }
                        CommonResult body = response.body();
                        JSONObject data = (JSONObject) body.getData();
                        Topic tableTopic = data.getObject("topic", Topic.class);
                        Intent intent = new Intent(context, TopicDetailsActivity.class);
                        intent.putExtra(Constant.EXTRA_INFO_TOPIC, tableTopic);
                        context.startActivity(intent);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                    }
                });

    }

}
